﻿using System;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using Brettle.Web.NeatUpload;
using System.Linq;
using System.Collections.Generic;

namespace HealthCommunity.Controls
{
	public partial class UCCourseEdit : System.Web.UI.UserControl
	{
		private ICourseProvider _CourseProvider;
		private List<DrugStore> lstDrugStore;

		public string ServerURL
		{
			get
			{
				if(Request.Url.Port > 0)
				{
					return string.Format("http://{0}:{1}", Request.Url.Host, Request.Url.Port.ToString());
				}
				else
				{
					return "http://" + Request.Url.Host;
				}
			}
		}

		public int CurrentCourseID
		{
			get
			{
				var id = CommonHelper.QueryStringInt("courseid");

				if(id <= 0)
				{
					if(ViewState["CourseID"] != null)
					{
						id = (int)ViewState["CourseID"];
					}
				}

				return id;
			}
			set
			{
				ViewState["CourseID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindCourseCategory();
				BindDrugStore();

				if(CurrentCourseID > 0)
				{
					BindCourse();
				}
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			fscoursechapter.Visible = (CurrentCourseID > 0);
			fscoursechapterlist.Visible = (CurrentCourseID > 0);
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			var theCourse = new Course() { CourseName = txtCourseName.Text.Trim(), CourseDescription = txtCourseDescription.Text.Trim(), CourseCateogryID = int.Parse(ddlCourseCategory.SelectedValue) };

			if(_CourseProvider == null)
			{
				_CourseProvider = new CourseProvider();
			}

			var msg = string.Empty;

			theCourse.IsPublic = chbIsPublic.Checked ? 1 : 0;

			if(CurrentCourseID <= 0)
			{
				var u = SiteContext.Current.CurrentUser;

				if(u != null)
				{
					theCourse.DrugStoreID = u.DrugStoreID;
				}

				theCourse.CourseAddDate = DateTime.Now;

				theCourse = _CourseProvider.CreateCourse(theCourse, out msg);

				if(theCourse != null)
				{
					CurrentCourseID = theCourse.CourseID;
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_CourseAndShareTo> lstNewCourseAndShareTo = new List<RLT_CourseAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltCourseAndShareTo = new RLT_CourseAndShareTo() { CourseID = CurrentCourseID, ShareToDrugStoreID = id };
								lstNewCourseAndShareTo.Add(rltCourseAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltCourseAndShareTo = new RLT_CourseAndShareTo() { CourseID = CurrentCourseID, ShareToMemberID = memberID };
								lstNewCourseAndShareTo.Add(rltCourseAndShareTo);
							}
						}

						if(lstNewCourseAndShareTo.Count > 0)
						{
							_CourseProvider.CreateCourseAndShareTo(lstNewCourseAndShareTo);
						}
					}

					ltrMsg.Text = "课程创建成功,接下来您可以继续添加课程章节";
				}
				else
				{
					ltrMsg.Text = "课程创建失败: " + msg;
				}
			}
			else
			{
				theCourse.CourseID = CurrentCourseID;

				if(_CourseProvider.UpDateCourse(theCourse))
				{
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_CourseAndShareTo> lstCourseAndShareTo = new List<RLT_CourseAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltCourseAndShareTo = new RLT_CourseAndShareTo() { CourseID = CurrentCourseID, ShareToDrugStoreID = id };
								lstCourseAndShareTo.Add(rltCourseAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltCourseAndShareTo = new RLT_CourseAndShareTo() { CourseID = CurrentCourseID, ShareToMemberID = memberID };
								lstCourseAndShareTo.Add(rltCourseAndShareTo);
							}
						}

						_CourseProvider.SaveCourseAndShareTo(CurrentCourseID, lstCourseAndShareTo);
					}

					ltrMsg.Text = "课程保存成功";

					if(!string.IsNullOrEmpty(txtCourseChapterName.Text.Trim()))
					{
						if(CreateCourseChapter())
						{
							BindCourse();
						}
					}
				}
				else
				{
					ltrMsg.Text = "课程保存失败";
				}
			}
		}

		private bool CreateCourseChapter()
		{
			var theNewCourseChapter = new CourseChapter() { CourseID = CurrentCourseID };

			theNewCourseChapter.CourseChapterName = txtCourseChapterName.Text.Trim();
			var credits = 0;
			if(int.TryParse(txtRequiredCredits.Text.Trim(), out credits))
			{
				theNewCourseChapter.CourseChapterReqiredCredits = credits;
			}

			theNewCourseChapter.CourseChapterVideoAddress = txtVideoAddress.Text.Trim();
			if(fuFront.HasFile)
			{
				string[] imgFileType = { ".jpg", ".jpeg", ".gif", ".png", ".bmp" };

				if(imgFileType.Contains(System.IO.Path.GetExtension(fuFront.FileName)))
				{
					theNewCourseChapter.CourseChapterFront = fuFront.FileBytes;
				}
			}

			if(iLocalFile.HasFile)
			{
				if(System.IO.Path.GetExtension(iLocalFile.FileName).Equals(".flv"))
				{
					var fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(iLocalFile.FileName);
					theNewCourseChapter.CourseChapterVideoAddress = ServerURL + "/Videos/" + fileName;
					iLocalFile.MoveTo(Server.MapPath("~/Videos/") + fileName, MoveToOptions.Overwrite);
				}
			}

			if(_CourseProvider == null)
			{
				_CourseProvider = new CourseProvider();
			}

			var msg = string.Empty;
			theNewCourseChapter = _CourseProvider.CreateCourseChapter(theNewCourseChapter, out msg);

			return (theNewCourseChapter != null);
		}

		private void BindCourseCategory()
		{
			if(_CourseProvider == null)
			{
				_CourseProvider = new CourseProvider();
			}

			ddlCourseCategory.Items.Clear();

			ddlCourseCategory.DataSource = _CourseProvider.GetAllCourseCategory();
			ddlCourseCategory.DataBind();
		}

		private void BindCourse()
		{
			if(CurrentCourseID > 0)
			{
				if(_CourseProvider == null)
				{
					_CourseProvider = new CourseProvider();
				}

				var theCourse = _CourseProvider.GetCourse(CurrentCourseID);

				if(theCourse != null)
				{
					txtCourseName.Text = theCourse.CourseName;
					txtCourseDescription.Text = theCourse.CourseDescription;
					foreach(ListItem item in ddlCourseCategory.Items)
					{
						item.Selected = (item.Value.Equals(theCourse.CourseCateogryID.GetValueOrDefault().ToString()));
					}

					if(theCourse.IsPublic != 1)
					{
						var courseAndShareTo = _CourseProvider.GetCourseAndShareToByCourse(CurrentCourseID);

						if(courseAndShareTo != null && courseAndShareTo.Count > 0)
						{
							var courseAndShareToDrugStore = courseAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
							var courseAndShareToMember = courseAndShareTo.Where(vs => vs.ShareToMemberID > 0);

							if(courseAndShareToDrugStore != null)
							{
								var lstCourseShareToDrugStore = courseAndShareToDrugStore.ToList();

								if(lstCourseShareToDrugStore.Count > 0)
								{
									foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
									{
										var drugStoreID = int.Parse(item.Value);

										item.Selected = lstCourseShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
									}
								}
							}

							lstMemberSelected.Items.Clear();

							if(courseAndShareToMember != null)
							{
								var lstCourseShareToMember = courseAndShareToMember.ToList();

								if(lstCourseShareToMember.Count > 0)
								{
									var data = from vs in lstCourseShareToMember
														 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

									foreach(var dataItem in data)
									{
										var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

										//if (!lstMemberSelected.Items.Contains(item))
										//{
										lstMemberSelected.Items.Add(item);
										//}
									}
								}
							}
						}
					}

					rptCourseChapter.DataSource = _CourseProvider.GetCourseChapterByCourse(theCourse.CourseID);
					rptCourseChapter.DataBind();

					rptCourseChapter.DataSource = _CourseProvider.GetCourseChapterByCourse(CurrentCourseID);
					rptCourseChapter.DataBind();
				}
			}
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}
	}
}